package com.app.mycoffee2_1.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.mycoffee2_1.R;
import com.app.mycoffee2_1.adapter.ProductAdapter;
import com.app.mycoffee2_1.api.Api;
import com.app.mycoffee2_1.api.ApiConfig;
import com.app.mycoffee2_1.api.CoffeeCallback;
import com.app.mycoffee2_1.manager.LoginInfoManager;
import com.app.mycoffee2_1.model.Order;
import com.app.mycoffee2_1.model.OrderItem;
import com.app.mycoffee2_1.model.Product;
import com.app.mycoffee2_1.model.Result;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.FormBody;

public class ProductFragment extends BaseFragment {
    private RecyclerView recyclerView;
    private final List<Product> products = new ArrayList<>();
    ProductAdapter productAdapter = null;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                productAdapter.setProducts(products);
                productAdapter.notifyDataSetChanged();
            }
        }
    };

    public ProductFragment() {
    }

    public static ProductFragment newInstance() {
        return new ProductFragment();
    }


    @Override
    protected int initLayout() {
        return R.layout.fragment_product;
    }

    @Override
    public void initView() {
        TextView title = mRootView.findViewById(R.id.title);
        recyclerView = mRootView.findViewById(R.id.productLV);
        title.setText("商品");
    }

    @Override
    protected void initData() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        productAdapter = new ProductAdapter(Objects.requireNonNull(getActivity()));
        productAdapter.setOnItemBtnClickListener(new ProductAdapter.OnItemBtnClickListener() {
            @Override
            public void onAddShoppingCartBtnClick(int position) {
                HashMap<String, Object> params = new HashMap<>();
                params.put("userId", LoginInfoManager.getInstance().getUserId(Objects.requireNonNull(getActivity())));
                params.put("productId", products.get(position).getId());
                params.put("num", 1);
                addShoppingCart(getActivity(), params);
                Toast.makeText(getActivity(), "点击购物车", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onBuyBtnClick(int position) {
                Order order = new Order();
                order.setUserId(LoginInfoManager.getInstance().getUserInfo(Objects.requireNonNull(getActivity())).getUserId());
                order.setTotalPrice(BigDecimal.valueOf(39.00));
                ArrayList<OrderItem> orderItems = new ArrayList<>();
                OrderItem orderItem = new OrderItem();
                orderItem.setGoodsId(products.get(position).getId());
                orderItem.setGoodsCount(1);
                orderItem.setGoodsName(products.get(position).getName());
                orderItem.setSellingPrice(products.get(position).getPrice());
                orderItems.add(orderItem);
                order.setItemVOList(orderItems);
                String orderJson = new Gson().toJson(order);

                FormBody formBody = new FormBody.Builder()
                        .add("orderJson", orderJson)
                        .build();

                byProduct(formBody);

                Toast.makeText(getActivity(), "点击购买", Toast.LENGTH_SHORT).show();
            }
        });
        recyclerView.setAdapter(productAdapter);
        getAllProducts(getActivity(), null);
    }

    public void getAllProducts(Context context, HashMap<String, Object> params) {
        Api.config(ApiConfig.PRODUCT_LIST_ALL, params).getRequest(context, new CoffeeCallback() {
            @Override
            public void onSuccess(String res) {
                Result<List<Product>> result = new Gson().fromJson(res, new TypeToken<Result<List<Product>>>() {
                }.getType());
                if (result.getResultCode()!=null&&result.getResultCode() == 200) {
                    products.removeAll(products);
                    products.addAll(result.getData());
                    mHandler.sendEmptyMessage(0);
                }
                System.out.println(result.getMessage());
            }

            @Override
            public void onFailure(Exception e) {
                System.out.println(e);
            }
        });
    }

    public void addShoppingCart(Context context, HashMap<String, Object> params) {
        Api.config(ApiConfig.SHOPPING_CART_ADD, params).getRequest(context, new CoffeeCallback() {
            @Override
            public void onSuccess(String res) {
                Result result = new Gson().fromJson(res, Result.class);
                if (result.getResultCode()!=null&&result.getResultCode() == 200) {
                    // TODO
                }
                System.out.println(result.getMessage());
            }

            @Override
            public void onFailure(Exception e) {
                System.out.println(e);
            }
        });
    }

    public void byProduct(FormBody formBody) {
        Api.config(ApiConfig.ORDER_ADD, formBody).postRequest(new CoffeeCallback() {
            @Override
            public void onSuccess(String res) {
                Result result = new Gson().fromJson(res, Result.class);
                if (result.getResultCode()!=null&&result.getResultCode() == 200) {
                    // TODO
                }
                System.out.println(result.getMessage());
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }
}
